import { CancellationToken, DefinitionProvider, Location, Position, TextDocument, Uri } from 'vscode';
import { Config } from './lib/config'
import * as path from "path";
import * as fs from "fs";

export class JsonDefinitionProvider implements DefinitionProvider {
  constructor(public config: Config) {}

  public provideDefinition(document: TextDocument, position: Position, token: CancellationToken) {
    const textLine = document.lineAt(position);
    const filePath = document.fileName;
    const locs: Location[] = []

    const paths = textLine.text.split(":");
    if (paths.length < 1) {
      return locs;
    }

    let textPath = paths[1].replace(/(,|\s|\'|\")/g, '');
    textPath = textPath.trim().replace(/^@/, "");

    let roots = this.config.getResolveRoots(document);
    const curDir = path.dirname(filePath);
    let file;
    const exts = [".ts", ".js"];

    if (textPath.startsWith("/")) {
      // 绝对路径
      outer:
      for (const root of roots) {
        for (const ext of exts) {
          let _path = path.join(root, textPath + ext);
          if (fs.existsSync(_path)) {
            file = _path;
            break outer;
          }
        }
      }
    } else {
      for (const ext of exts) {
        let _path = path.resolve(curDir, textPath + ext);
        if (fs.existsSync(_path)) {
          file = _path;
          break;
        }
      }
    }

    if (file) {
      locs.push(new Location(Uri.file(file), new Position(0 ,0)));
    }

    return locs;
  }
} 